﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace CsvLib
{
    /// <summary>
    /// 以流的方式读取csv文件
    /// </summary>
    public class CsvStreamReader
    {
        readonly string path;
        readonly Title title;
        StreamReader sr;

        /// <summary>
        /// 如果提升标题可以对 Line 使用 ["标题字符串"] 索引列
        /// </summary>
        /// <param name="path">csv文件路径</param>
        /// <param name="isImproveTitle">是否提升标题</param>
        public CsvStreamReader(string path, bool isImproveTitle)
        {
            this.path = path;
            sr = new StreamReader(path);
            if (isImproveTitle)
            {
                Dictionary<string, int> stringToInt = new Dictionary<string, int>();
                List<string> list = new List<string>();

                string line = sr.ReadLine();
                string[] titles = line.Split(',');
                for (int i = 0; i < titles.Length; i++)
                {
                    stringToInt.Add(titles[i], i);
                    list.Add(titles[i]);
                }
                title = new Title(stringToInt, list);
            }
        }

        public void Foreach(Action<Line> action)
        {
            sr = new StreamReader(path);

            if (title != null)
            {
                sr.ReadLine();
            }

            int lineIndex = 0;

            while (!sr.EndOfStream)
            {
                string[] data = sr.ReadLine().Split(',');
                Line line = new Line(title, data, lineIndex++);
                action.Invoke(line);
            }
        }
    }
}
